package com.pacs.control;

import java.net.URLEncoder;
import java.util.List;
import com.pacs.service.WeixinService;
import com.pacs.model.UserWechats;
import com.pacs.model.Users;
import com.pacs.service.AccountService;
import com.pacs.service.ServiceFactory;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.redis.Redis;

public class WeixinWebController extends Controller {

	private static String WEB_BASR_URL = "http://wechat.pacsonline.cn/pacs_online/html";
	
	public void addBinding() {
		this.process(WEB_BASR_URL+"/bind.html?address=hlj");
	}
	
	public void report() {
		this.process(WEB_BASR_URL+"/report_list.html");
	}

	public void aboutUs() {
		this.process(WEB_BASR_URL+"/aboutAs_hlj.html");
	}
	
	public void mainPage() {
		this.process(WEB_BASR_URL+"/html/index/index_v1.html");
	}
	
	public void ris() {
		this.process("http://ris.pacsonline.cn");
	}
	
	private void process(String toUrl) {
		try {
			String encodeUrl = URLEncoder.encode(toUrl, "UTF-8");
			Object sessionObj = this.getRequest().getSession().getAttribute("wxUserInfo");
			if (sessionObj == null) {
				String code = this.getPara("code");
				if (code == null) {
					this.redirectToWX();
					return;
				}
				WeixinService wService = ServiceFactory.getService(WeixinService.class);
				String openId = wService.getOpenId(code);
				UserWechats userWechats = UserWechats.dao.findById(openId);
				if (userWechats == null) {
					AccountService aService = ServiceFactory.getService(AccountService.class);
	                aService.createWxUser(openId);
	                userWechats = UserWechats.dao.findById(openId);
				}
				Users users = Users.dao.findById(userWechats.getUid());
				this.getRequest().getSession().setAttribute("wxUserInfo", userWechats);

				String uidStr = toUrl.contains("?") ? "&uid=" : "?uid=";
				this.redirect(toUrl + uidStr + userWechats.getUid());
			} else {
				UserWechats userWechats = (UserWechats) sessionObj;
				Users users = Users.dao.findById(userWechats.getUid());
				this.getRequest().getSession().setAttribute("wxUserInfo", userWechats);

				String uidStr = toUrl.contains("?") ? "&uid=" : "?uid=";
				this.redirect(toUrl + uidStr + userWechats.getUid());
			}
		} catch (Exception e) {
			// nothing
		}
		
	}

	// 跳转到微信认证
	public void redirectToWX() {
		String url = getRequest().getRequestURL().toString();
		if (getPara("type") !=null) {
			url = url + "?type=" + getPara("type");
		}
		// String url = "http://4wzz8b.natappfree.cc/wx/my";
		try {
			url = URLEncoder.encode(url, "UTF-8");
		} catch (Exception e) {
			// nothing
		}
		String redirect = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo#wechat_redirect";
		redirect(String.format(redirect, PropKit.get("appId"), url));
	}
	
}
